package lt.hsu.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lt.hsu.thr.EWrapThr;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ConvertResponseBody implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查注解，如果存在 @NoWrap 注解，则不包装返回值
        return !returnType.hasMethodAnnotation(NoWrap.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 获取请求的URI
        String requestPath = request.getURI().getPath();

        // 检查URI是否为Swagger相关的资源，如果是，则不进行后续处理
        if (requestPath.startsWith("/swagger") || requestPath.startsWith("/v2/api-docs") || requestPath.startsWith("/v3/api-docs")) {
            return body;
        }
        if (body instanceof ApiResponse) {
            // 如果返回值已经是 ApiResponse 类型，则不进行包装
            return body;
        } else if (body instanceof String) {
            // 因为 String 类型的数据会使用 StringHttpMessageConverter 进行处理
            // 所以需要转换为 JSON 字符串，否则会报错
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.writeValueAsString(ApiResponse.success(body));
            } catch (JsonProcessingException e) {
                throw EWrapThr.SYS_ERROR_WRAP.toThr();
            }
        } else {
            // 对其他类型的返回值进行包装
            return new ApiResponse<>(EApiReturn.SUCCESS,body);
        }
    }
}